<?php


namespace broadcast\services;

/**
 * 红包处理
 * Class UtilService
 * @package broadcast\services
 */
class Envelopes
{
    public $bonus;//红包
    public $bonusNum;//红包个数
    public $bonusMoney;//红包总金额
    public $moneySingleMax;//单个红包最大限制
    public $moneySingleMin;//单个红包最小限制

    //此算法数量大 会出现一定的总金额偏差

    //设置数据
    public function __construct($bonusNum = 20, $bonusMoney = 200)
    {
        $avg     = ceil($bonusMoney / $bonusNum);
        $avgHalf = ceil($avg / 2);
     
        $this->bonusNum       = $bonusNum;
        $this->bonusMoney     = $bonusMoney;
        $this->moneySingleMax = $avg + $avgHalf;
        if (ceil($bonusMoney / $bonusNum)>1 && $avg - $avgHalf < 1){
            $this->moneySingleMin = 1;
        }else{
            $this->moneySingleMin = $avg - $avgHalf;
        }
    }

    //设置一个红包的金额
    private function randomFloat($min = 0, $max = 1)
    {
        $mtRand       = mt_rand();
        $mtGetRandMax = mt_getrandmax();
        return $min + $mtRand / $mtGetRandMax * ($max - $min);
    }

    //计算
    public function compute()
    {
        $this->bonus    = array();
        $bonusMoneyTemp = $this->bonusMoney;
        $moneySingleMax = $this->moneySingleMax;
        $moneySingleMin = $this->moneySingleMin;
        $i              = 1;
        while ($i < $this->bonusNum) {
            if ($moneySingleMax > $bonusMoneyTemp) {
                $moneySingleMax = floatval(sprintf("%01.2f", $bonusMoneyTemp / 2));//剩余金额不够分时,把剩余金额的一半作为备用金
                if ($moneySingleMin > $moneySingleMax) { //最小金额大于最大金额时，将最小金额设置为最大金额的一半
                    $moneySingleMin = floatval(sprintf("%01.2f", $moneySingleMax / 2));
                }
            }
            $bonusMoneyRad  = $this->randomFloat($moneySingleMin, $moneySingleMax);//一个红包随机金额
            $bonusMoneyRad  = floatval(sprintf("%01.2f", $bonusMoneyRad));
            $bonusMoneyTemp = $bonusMoneyTemp - $bonusMoneyRad;//待分配的总剩余金额
            $bonusMoneyTemp = floatval(sprintf("%01.2f", $bonusMoneyTemp));
            $this->bonus[]  = $bonusMoneyRad;
            $i++;
        }
        $this->bonus[] = $bonusMoneyTemp;//分配剩余金额给最后一个红包
        return $this->bonus;
        
    }

}